<template>
  <view class="app">
    <view class="main-box">
      <view class="address-box">
        <view v-if="address.id" @click="selectAddress()">
          <view class="address-title">
            <text>{{ address.province }}</text>
            <text>{{ address.city }}</text>
            <text>{{ address.area }}</text>
            <text class="address-mark address-default" v-if="address.is_default == 1">默认</text>
            <text class="address-mark address-tag" v-if="address.tag > 0">{{
              ['', '家', '公司', '学校'][address.tag]
            }}</text>
          </view>
          <view class="address-detail">
            <text class="pr-38rpx">{{ address.address }}</text>
            <u-icon class="address-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
          <view class="address-receiver">
            <text class="mr-20rpx">{{ address.receiver }}</text>
            <text>{{ address.phone }}</text>
          </view>
        </view>
        <view v-else @click="selectAddress()">
          <view class="address-add">
            <u-icon size="28" color="#232323" name="plus"></u-icon>
            <text class="pl-10rpx font-bold">增加收货地址</text>
          </view>
        </view>
      </view>

      <view class="goods-box">
        <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
          <view class="item-left">
            <view class="goods-logo">
              <image :src="item.goods_logo"></image>
            </view>
          </view>
          <view class="item-right">
            <view class="goods-name">{{ item.goods_name }}</view>
            <text class="desc-box" v-if="item.goods_desc">
              <text class="goods-desc line-2">{{ item.goods_desc }}</text>
            </text>
            <view class="goods-bottom">
              <text class="goods-price">{{ item.goods_price }}</text>

              <view class="num-box">
                <view class="minus-btn" @click.stop="minusNum(item)">
                  <u-icon name="minus" size="23" :color="item.num_minus ? 'black' : 'lightgray'"></u-icon>
                </view>
                <input
                  class="goods-num"
                  type="number"
                  v-model.number="item.goods_num"
                  @blur="checkNum(item)"
                  maxlength="3"
                />
                <view class="plus-btn" @click.stop="plusNum(item)">
                  <u-icon name="plus" size="23" :color="item.num_plus ? 'black' : 'lightgray'"></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="account-box">
        <view class="account-item">
          <view class="flex-row flex-row-bottom-start">
            <text>商品总价</text>
            <text class="total-num">共 {{ goodsList.length }} 件商品</text>
          </view>
          <text class="money">{{ goodsAmount }}</text>
        </view>
        <view class="account-item">
          <text>运费</text>
          <text class="font-bold" v-if="freight == '0'">包邮</text>
          <text class="money" v-else>{{ freight }}</text>
        </view>
        <view class="account-item total-item">
          <text>合计</text>
          <text class="money">{{ totalAmount }}</text>
        </view>
      </view>

      <view class="single-box">
        <view class="single-item" @click="showWin = true">
          <text class="single-title">支付方式</text>
          <view class="single-right">
            <view class="flex items-center">
              <image mode="widthFix" class="w-5 mr-1" :src="payWay.logo" />
              <text>{{ payWay.title }}</text>
            </view>
            <u-icon class="right-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
        </view>

        <u-popup v-model="showWin" mode="bottom" border-radius="20">
          <view class="drawer-box">
            <view class="pay-item" v-for="(item, key) in payOptions" :key="key">
              <view class="flex items-center">
                <image mode="widthFix" class="w-5 mr-3" :src="item.logo" />
                <text class="font-size-30rpx">{{ item.title }}</text>
              </view>
              <u-radio-group v-model="payWay.value">
                <u-radio
                  active-color="orange"
                  shape="circle"
                  size="35"
                  :name="item.value"
                  @change="changePayWay"
                ></u-radio>
              </u-radio-group>
            </view>
          </view>
        </u-popup>
      </view>

      <view class="single-box" v-if="payWay.value > 20">
        <view class="single-item">
          <text class="single-title">支付凭证</text>
          <view class="single-right" @click="uploadVoucher()">
            <view class="w-20 h-20 bg-gray-1 mr-1 p-2 rd-2" v-for="(item, index) in voucher" :key="index">
              <image class="w-full h-full" mode="aspectFit" :src="item" @click.stop="preview(index)" />
            </view>
            <u-icon class="right-icon voucher-icon" size="26" color="#b7b7b7" name="arrow-right"></u-icon>
          </view>
        </view>
      </view>

      <view class="single-box">
        <view class="single-item">
          <text class="single-title">订单留言</text>
          <input
            type="text"
            maxlength="300"
            v-model="remark"
            cursor-spacing="19"
            placeholder="留言建议提前协商"
          />
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="footer-left">
        <text>应付：</text>
        <text class="pay-price">{{ totalAmount }}</text>
      </view>
      <view class="pay-btn" @click="submitOrder()"> 提交 </view>
    </view>

    <!-- 凭证支付 -->
  </view>
</template>

<script lang="ts" setup>
  import calc from '@/utils/math';
  import { ref, computed, watch } from 'vue';
  import { getOrderGoods, getOrderAddress, createOrder, getOrderFreight } from '@/api/goods/order';
  import { delGoodsCart } from '@/api/goods/cart';
  import { useCartStore } from '@/store/cart';
  import { uploadImg } from '@/common/upload';
  import { onLoad, onUnload } from '@dcloudio/uni-app';
  import { report } from '@/utils/exception';
  import { msg } from '@/utils/msg';
  import type { BuyGoodsItem, PayWay, WechatPayment } from '@/types/order';
  import type { FansAddress } from '@/types/fans';

  const showWin = ref<boolean>(false);
  const cartStore = useCartStore();
  const address = ref({} as FansAddress);
  const goodsList = ref<BuyGoodsItem[]>([]);
  // 邮费
  const freight = ref<string>('0');
  const remark = ref<string>('');

  let addressId = 0; // 地址ID
  let cartIds = ''; // 购物车ID
  let orderGoods = ''; // 订单商品参数

  const payOptions: PayWay[] = [
    {title:'微信支付',logo:'/static/icon/img/order/pay-wechat.png',value:11},
    // { title: '微信凭证', logo: '/static/icon/img/order/pay-wechat.png', value: 21 },
    // { title: '支付宝凭证', logo: '/static/icon/img/order/pay-alibaba.png', value: 22 },
    // { title: '银联凭证', logo: '/static/icon/img/order/pay-union.png', value: 23 },
  ];

  const payWay = ref<PayWay>({ ...payOptions[0] });
  const voucher = ref<string[]>([]);

  const getAddress = () => {
    getOrderAddress(addressId)
      .then((res) => {
        if (res.data) {
          address.value = res.data;
          addressId = address.value.id;
          updateFreight();
        }
      })
      .catch((err) => {
        report(err);
      });
  };

  // 获取运费
  const updateFreight = () => {
    if (addressId == 0) {
      freight.value = '0';
      return;
    }

    // @todo 请求服务器获取运费
    // msg.loading();
    // getOrderFreight(addressId, orderGoods)
    //   .then((res) => {
    //     console.log(res);
    //     freight.value = res.data.result.fee;
    //     msg.hideLoading();
    //   })
    //   .catch((err) => {
    //     report(err);
    //   });
    freight.value = '0';
  };

  onLoad((option: any) => {
    cartIds = option.cart_ids;
    orderGoods = option.order_goods;
    getAddress();

    // const order_goods = '13@8@2|14@9@1';
    getOrderGoods(orderGoods)
      .then((res) => {
        goodsList.value = res.data;
        console.log(goodsList.value);
        goodsList.value.forEach((item: BuyGoodsItem) => {
          initNum(item);
        });
      })
      .catch((err) => {
        report(err);
      });

    uni.$on('changeAddress', (data) => {
      addressId = data.address_id;
      getAddress();
    });
  });

  onUnload(() => {
    uni.$off('changeAddress');
  });

  const initNum = (goodsItem: BuyGoodsItem) => {
    if (goodsItem.goods_stock <= 0) {
      goodsItem.num_minus = false;
      goodsItem.num_plus = false;
      return;
    }
    checkNum(goodsItem);
  };

  const checkNum = (goodsItem: BuyGoodsItem) => {
    if (goodsItem.goods_num < goodsItem.goods_stock) {
      goodsItem.num_plus = true;
      if (goodsItem.goods_num >= 999) {
        goodsItem.goods_num = 999;
        goodsItem.num_plus = false;
      }
    } else {
      goodsItem.goods_num = goodsItem.goods_stock;
      goodsItem.num_plus = false;
    }

    if (goodsItem.goods_num > 1) {
      goodsItem.num_minus = true;
    } else {
      goodsItem.goods_num = 1;
      goodsItem.num_minus = false;
    }
  };

  const minusNum = (goodsItem: BuyGoodsItem) => {
    if (!goodsItem.num_minus) return;
    goodsItem.goods_num--;
    checkNum(goodsItem);
  };

  const plusNum = (goodsItem: BuyGoodsItem) => {
    if (!goodsItem.num_plus) return;
    goodsItem.goods_num++;
    checkNum(goodsItem);
  };

  const selectAddress = () => {
    uni.navigateTo({ url: '/pages/address/index?from=order' });
  };

  // 商品金额
  let goodsTotalMoney = 0;
  const goodsAmount = computed(() => {
    goodsTotalMoney = goodsList.value.reduce((prev: number, next: BuyGoodsItem) => {
      return calc.add(prev, calc.mul(next.goods_num, parseFloat(next.goods_price)));
    }, 0);
    return isNaN(goodsTotalMoney) ? 0 : goodsTotalMoney;
  });

  // 合计金额
  const totalAmount = computed(() => {
    return calc.add(goodsAmount.value, parseFloat(freight.value));
  });

  watch(
    () => goodsList.value,
    () => {
      orderGoods = '';
      goodsList.value.forEach((item) => {
        if (orderGoods) orderGoods += '|';
        if (item.goods_num > 0) {
          orderGoods += `${item.goods_id}@${item.goods_specs_id}@${item.goods_num}`;
        }
      });
      updateFreight();
    },
    { deep: true }
  );

  // 选择支付方式
  const changePayWay = async (e: any) => {
    await new Promise((resolve) => {
      resolve(e);
    });

    let selectedPayWay = payOptions.find((item: PayWay) => item.value == payWay.value.value);
    payWay.value.title = (selectedPayWay as PayWay).title;
    payWay.value.logo = (selectedPayWay as PayWay).logo;
    showWin.value = false;
  };

  // 上传凭证
  const uploadVoucher = () => {
    uploadImg()
      .then((res: any) => {
        // console.log(res);
        voucher.value = res;
      })
      .catch((err) => {
        msg.error(err);
      });
  };

  // 预览凭证
  const preview = (index: number) => {
    uni.previewImage({
      urls: voucher.value,
      current: voucher.value[index], // 当前显示图片的链接
    });
  };

  // 提交订单
  const submitOrder = () => {
    if (addressId == 0) {
      return msg.error('请选择收货地址');
    }

    if (!orderGoods) {
      return msg.error('订单异常，请重新下单');
    }

    if (payWay.value.value > 20 && voucher.value.length == 0) {
      return msg.error('请上传支付凭证');
    }

    // return false;
    msg.loading('提交中');
    createOrder(addressId, orderGoods, payWay.value.value, voucher.value.join('|'), remark.value)
      .then((resp) => {
        switch (payWay.value.value) {
          case 11:
            msg.loading('支付中');
            setTimeout(() => {
              wechatPay(resp.data.order_no, resp.data.jspay);
            }, 600);
            break;

          default:
            msg.success('提交成功');
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/order/index?status=20' });
            }, 2000);
            break;
        }

        // 购物车删除商品
        if (cartIds) {
          const cartIdsArr = cartIds.split(',');
          delGoodsCart(cartIdsArr)
            .then((res) => {
              cartStore.cartReload = 2;
              const leftCartNum = cartStore.cartNum - cartIdsArr.length;
              cartStore.cartNum = leftCartNum <= 0 ? 0 : leftCartNum;
            })
            .catch((err) => {
              report(err);
            });
        }
      })
      .catch((err) => {
        report(err);
      });
  };

  // 微信支付
  const wechatPay = (orderNo: string, jspay: WechatPayment) => {
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: '', // 微信支付可以为空
      timeStamp: jspay.timeStamp, // 时间戳（单位：秒）
      nonceStr: jspay.nonceStr, // 随机字符串
      package: jspay.package, // 带有预支付prepay_id参数
      signType: jspay.signType, // 签名类型
      paySign: jspay.paySign, // 支付签名

      success: function (res) {
        // console.log(res);
        msg.success('支付成功');
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/order/index?status=30' });
        }, 2000);
      },
      fail: function (err) {
        // console.log('支付失败:');
        // console.log(err);
        msg.hideLoading();

        if (err.errMsg == 'requestPayment:fail cancel') {
          // 用户取消支付
        } else {
        }

        uni.redirectTo({ url: '/pages/order/detail?order_no=' + orderNo });
      },
    });
  };

  // @todo第三方支付
</script>

<style lang="scss" scoped>
  .main-box {
    margin: 15rpx 25rpx 125rpx;

    .address-box {
      position: relative;
      background: #ffffff;
      padding: 24rpx 25rpx;
      border-radius: 20rpx;
      overflow: hidden;

      &:before {
        position: absolute;
        right: 0;
        bottom: 0;
        left: 0;
        height: 6rpx;
        background: linear-gradient(
          -45deg,
          transparent 0,
          transparent 10%,
          #ff6c6c 10%,
          #ff6c6c 42%,
          transparent 42%,
          transparent 58%,
          #1989fa 58%,
          #1989fa 90%,
          transparent 90%,
          transparent 100%
        );
        background-size: 120rpx;
        content: '';
      }

      .address-title {
        display: flex;
        font-size: 28rpx;

        .address-mark {
          display: flex;
          justify-content: center;
          font-size: 22rpx;
          border-radius: 15rpx;
          padding: 4rpx 0;
          width: 62rpx;
          margin-left: 10rpx;
          font-weight: normal;
        }

        .address-default {
          color: white;
          background: #fc4644;
        }

        .address-tag {
          color: #cd2d2a;
          background: #fdf2f2;
        }
      }

      .address-detail {
        display: flex;
        align-items: center;
        font-size: 32rpx;
        font-weight: 600;
        margin: 15rpx 0;
        position: relative;

        .address-icon {
          // width:50rpx;
          // flex:none;
          position: absolute;
          right: 0rpx;
        }
      }

      .address-receiver {
        display: flex;
        font-size: 28rpx;
      }

      .address-add {
        display: flex;
        align-items: center;
        padding: 10rpx 5rpx;
      }
    }

    .goods-box {
      margin-top: 15rpx;
      padding-top: 35rpx;
      border-radius: 20rpx;
      background: white;

      .goods-item {
        padding: 0 22rpx 35rpx 20rpx;
        display: flex;
        align-items: start;

        .item-left {
          display: flex;
          align-items: center;

          .goods-logo {
            margin-left: 5rpx;
            margin-right: 20rpx;

            image {
              width: 150rpx;
              height: 150rpx;
              border-radius: 20rpx;
            }
          }
        }

        .item-right {
          display: flex;
          flex-direction: column;
          flex: 1;

          .goods-name {
            font-size: 32rpx;
            font-weight: 600;
            display: inline-block;
            max-width: 445rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .desc-box {
            display: block;
          }
          .goods-desc {
            margin-top: 10rpx;
            font-size: 24rpx;
            color: #949494;
            background: #f5f5f5;
            padding: 5rpx 20rpx 5rpx 20rpx;
            border-radius: 10rpx;
          }

          .goods-bottom {
            margin-top: 12rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .goods-price {
              font-size: 35rpx;
              font-weight: 600;
              color: #fe5303;

              &::before {
                content: '￥';
                font-size: 22rpx;
              }
            }
          }

          .num-box {
            display: flex;
            align-items: center;
            border: 1px solid #dedede;
            border-radius: 50rpx;

            .minus-btn {
              padding: 8rpx 15rpx;
              border-right: 1px solid #dedede;
            }
            .plus-btn {
              padding: 8rpx 15rpx;
              border-left: 1px solid #dedede;
            }

            .goods-num {
              width: 55rpx;
              margin: 0 15rpx;
              font-size: 26rpx;
              text-align: center;
            }
          }
        }
      }
    }

    .account-box {
      margin-top: 15rpx;
      padding: 30rpx 25rpx 0;
      border-radius: 20rpx;
      background: white;

      .account-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 30rpx;
        padding-bottom: 30rpx;

        .total-num {
          margin-left: 15rpx;
          color: gray;
          font-size: 25rpx;
        }

        .money {
          font-weight: 600;

          &::before {
            content: '￥';
          }
        }
      }

      .total-item {
        padding-top: 25rpx;
        border-top: 1rpx solid #f5f5f5;
      }
    }

    .single-box {
      margin-top: 15rpx;
      padding: 25rpx;
      border-radius: 20rpx;
      background: white;

      .single-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 30rpx;

        .single-title {
          width: 140rpx;
          flex: none;
        }

        .single-right {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          flex: 1;
          color: gray;

          .right-icon {
            position: relative;
            top: 2rpx;
            left: 2rpx;
            margin-left: 10rpx;
          }

          .voucher-icon {
            margin-left: 20rpx;
          }
        }

        input {
          width: 100%;
          text-align: right;
        }
      }

      .drawer-box {
        height: 100%;
        padding: 30rpx 50rpx;

        .pay-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 90rpx;
          // padding-top: 30rpx;

          &:not(:last-child) {
            border-bottom: 1rpx solid #f5f5f5;
          }
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 110rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: white;
    padding: 0 35rpx;
    z-index: 2;

    .footer-left {
      display: flex;
      align-items: center;
      font-size: 30rpx;

      .pay-price {
        font-weight: 600;
        font-size: 38rpx;
        color: #fe5303;

        &::before {
          content: '￥';
        }
      }
    }

    .pay-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 250rpx;
      flex: none;
      font-size: 26rpx;
      font-weight: 600;
      color: white;
      padding: 24rpx 0;
      border-radius: 50rpx;
      letter-spacing: 1rpx;
      background-image: linear-gradient(to right, #f3204f, #f33720);
      box-shadow: rgba(255, 28, 0, 0.2) 0 5rpx 12rpx;
    }
  }
</style>
